<template>
    <div :class="['comment-item', `level-${level}`]">
      <div class="comment-header">
        <el-avatar :size="getAvatarSize(level)" :src="processedComment.avatarUrl || defaultAvatar" />
        <div class="comment-info">
          <div class="user-info">
            <span class="username">{{ processedComment.username || '未知用户' }}</span>
            <el-tag v-if="processedComment.isAuthor" size="small" type="success" class="author-tag">作者</el-tag>
          </div>
          <span class="time">{{ formatDate(processedComment.createdAt) }}</span>
        </div>
      </div>
      <div class="comment-content">{{ processedComment.content }}</div>
      <!-- 回复按钮和输入框 -->
      <div class="reply-form">
        <el-input
          v-model="replyContent"
          type="textarea"
          :rows="2"
          placeholder="回复评论..."
          :maxlength="200"
          show-word-limit
        />
        <el-button
          type="primary"
          size="small"
          @click="submitReply"
          :disabled="!replyContent.trim()"
          style="margin-top: 8px;"
        >回复</el-button>
      </div>
      <!-- 递归渲染子评论 -->
      <div v-if="processedComment.replies && processedComment.replies.length > 0" class="reply-section">
        <div class="reply-header" @click="toggleReplies">
          <span class="reply-count">{{ processedComment.replies.length }} 条回复</span>
          <el-icon :class="{ 'is-active': isExpanded }">
            <arrow-down />
          </el-icon>
        </div>
        <div v-show="isExpanded" class="reply-list">
          <RecursiveComment
            v-for="reply in processedComment.replies"
            :key="reply.id"
            :comment="reply"
            :level="level + 1"
            @submit-reply="emitReply"
          />
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed } from 'vue'
  import { ArrowDown } from '@element-plus/icons-vue'
  
  const props = defineProps({
    comment: { type: Object, required: true },
    level: { type: Number, default: 0 }
  })
  const emit = defineEmits(['submit-reply'])
  const replyContent = ref('')
  const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  const isExpanded = ref(false)
  
  // 获取当前用户ID
  const currentUserId = computed(() => {
    try {
      return JSON.parse(localStorage.getItem('userInfo'))?.id
    } catch (e) {
      return null
    }
  })
  
  // 处理评论数据，确保包含作者标识
  const processedComment = computed(() => ({
    ...props.comment,
    isAuthor: props.comment.hasOwnProperty('isAuthor') ? props.comment.isAuthor : props.comment.userId === currentUserId.value,
    replies: props.comment.replies?.map(reply => ({
      ...reply,
      isAuthor: reply.hasOwnProperty('isAuthor') ? reply.isAuthor : reply.userId === currentUserId.value
    }))
  }))
  
  function getAvatarSize(level) {
    // 层级越深头像越小
    return [40, 32, 28, 24, 20][Math.min(level, 4)]
  }
  function formatDate(dateString) {
    if (!dateString) return 'N/A'
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric', month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit', second: '2-digit'
    })
  }
  function submitReply() {
    emit('submit-reply', props.comment.id, replyContent.value)
    replyContent.value = ''
  }
  function emitReply(parentId, content) {
    emit('submit-reply', parentId, content)
  }
  function toggleReplies() {
    isExpanded.value = !isExpanded.value
  }
  </script>
  
  <style scoped>
  .comment-item {
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 12px;
    background: #fff; /* 默认背景，用于 level 0 */
    border: 1px solid #ebeef5;
  }
  .level-0 { /* 默认背景已设置在 .comment-item */ }
  .level-1 { background: #e3f6f5; /* 浅青色 */ }
  .level-2 { background: #fff7e6; /* 浅橙色 */ }
  .level-3 { background: #f0f9eb; /* 浅绿色 */ }
  .level-4 { background: #e6f7ff; /* 浅蓝色 */ }
  .level-5 { background: #f9f0ff; /* 浅紫色 */ }
  .level-6 { background: #fff0f6; /* 浅粉色 */ }
  .level-7 { background: #f6ffed; /* 浅浅绿色 */ }
  .level-8 { background: #e8f4ff; /* 极浅蓝色 */ }
  /* 更深层级将使用 level-8 的样式 */
  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }
  .comment-info {
    display: flex;
    flex-direction: column;
  }
  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .comment-info .username {
    font-weight: 500;
    color: #22577a;
    font-size: 15px;
  }
  .author-tag {
    font-size: 12px;
    padding: 0 6px;
    height: 20px;
    line-height: 18px;
    border-radius: 4px;
    background: linear-gradient(90deg, #b7e4c7 0%, #d8f3dc 100%);
    border: none;
    color: #40916c;
  }
  .comment-info .time {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }
  .comment-content {
    margin: 10px 0 8px 0;
    color: #333;
    font-size: 14px;
    line-height: 1.6;
  }
  .reply-section {
    margin-top: 12px;
  }
  .reply-header {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: background-color 0.3s;
  }
  .reply-header:hover {
    background-color: #f5f7fa;
  }
  .reply-count {
    font-size: 13px;
    color: #606266;
  }
  .reply-header .el-icon {
    transition: transform 0.3s;
  }
  .reply-header .el-icon.is-active {
    transform: rotate(180deg);
  }
  .reply-list {
    /* 移除固定左侧缩进，避免区域变小 */
    margin-top: 8px;
  }
  .reply-form {
    margin-left: 0;
    margin-top: 8px;
  }
  .nested-reply-item {
    padding: 12px;
    background: #fff;
  }
  </style>